package store

import (
	"os"
	"path/filepath"

	"gitee.com/zfd81/dbrs/config"
)

const (
	Table_Metadata = "system_metadata" //元数据信息表
	Table_User     = "system_user"     //用户信息表
)

var (
	storage Storage
	conf    = config.GetConfig()
)

func InitStorage() (err error) {
	path := filepath.Join(conf.DataDirectory, "data")
	info, err := os.Stat(path)
	if err != nil {
		if !os.IsExist(err) {
			os.Mkdir(path, 0777)
		} else {
			return err
		}
	} else if !info.IsDir() {
		os.Mkdir(path, 0777)
	}
	storage, err = New(filepath.Join(path, "dbrs.db"))
	storage.CreateTable(Table_User)
	return
}

func CreateTable(name string) error {
	return storage.CreateTable(name)
}

func Put(table string, key, value []byte) error {
	return storage.Put(table, key, value)
}

func BatchPut(table string, kvs []KeyValue) error {
	return storage.BatchPut(table, kvs)
}

func Get(table string, key []byte) ([]byte, error) {
	return storage.Get(table, key)
}

func GetWithPrefix(table string, prefix []byte) ([]*KeyValue, error) {
	return storage.GetWithPrefix(table, prefix)
}

func Delete(table string, key []byte) error {
	return storage.Delete(table, key)
}

func DeleteWithPrefix(table string, prefix []byte) error {
	return storage.DeleteWithPrefix(table, prefix)
}

func Truncate(table string) error {
	return storage.Truncate(table)
}

func Iterator(table string, f func(k, v []byte) error) error {
	return storage.Iterator(table, f)
}

func IteratorWithPrefix(table string, prefix []byte, f func(k, v string) error) error {
	return storage.IteratorWithPrefix(table, prefix, f)
}

func Count(table string) int64 {
	return storage.Count(table)
}
